<template>
  <div>
    <el-card class="search-card">
      <basic-form
        ref="formData"
        defaultExpandStatus
        :colNumOfRow="4"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        :handleClearForm="handleClearForm"
        @getFormData="getFormData"
      >
        <RemoteSelect
          ref="remoteSelect"
          slot="selectCustomer"
          placeholder="请选择客户"
          :optionKeys="['customerName', 'customerCode']"
          :echoValue="formData.customerCode"
          :echoOptions="[formData.customerName, formData.customerCode]"
          :remoteSelectOptions="remoteOptionsByCustomer"
          :handleClickButton="handleChooseCustomer"
          @getSelect="getCustomerInfoByRemote"
        />
      </basic-form>
    </el-card>
    <el-card class="table-card">
      <skus-table
        ref="skusTable"
        showSelectCol
        showActionCol
        :showPagination="isShowPagination"
        :tableHeight="480"
        :actionColWidth="200"
        :defaultMinWidth="100"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="pagination.total"
        :selectionChange="handleSelectionChange"
        :actionRender="renderTableBtnAction"
        :checkSelectable="checkSelectable"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <div slot="content_context">
          <!-- 按钮操作栏 -->
          <BtnRender :render="renderBtnsBar" />
        </div>
      </skus-table>
    </el-card>
    <!-- 选择客户弹框 -->
    <SelectCustomerDialog
      :visible.sync="dialogVisible.customer"
      @getSelectResults="getCustomerInfoByDialog"
    />
    <!-- 上架提示弹框 -->
    <ActionDialog
      actionType="1"
      dialogTitle="上架提示"
      :visible.sync="dialogVisible.batchUp"
      :okLoading="btnLoading.batchUp"
      :handleSubmit="batchUpTemporaryProjectGoods"
    />
    <!-- 修改预计下架日期弹框 -->
    <ActionDialog
      actionType="2"
      dialogTitle="修改预计下架日期"
      :visible.sync="dialogVisible.changeOffTime"
      :okLoading="btnLoading.changeOffTime"
      :handleSubmit="batchUpdateOffDate"
    />
    <!-- 换绑客户弹框 -->
    <ActionDialog
      actionType="3"
      dialogTitle="换绑客户"
      :visible.sync="dialogVisible.changeBindCustomer"
      :okLoading="btnLoading.changeBindCustomer"
      :handleSubmit="batchChangeBindCustomer"
    />
    <!-- 修改日志弹框 -->
    <ChangeLogDialog
      :skuNo="viewChangeLog.skuNo"
      :visible.sync="dialogVisible.viewChangeLog"
    />
    <!-- 高级查询弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="setTableDataBySeniorSearch"
    />
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import RemoteSelect from '@/pages/commodity/components/RemoteSelect';
import SelectCustomerDialog from '../components/SelectCustomerDialog';
import ActionDialog from '../components/ActionDialog';
import ChangeLogDialog from '../components/ChangeLogDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import { getBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { FORM_ITEMS, TABLE_COLUMNS, CacheKey } from './constants/list';
import { PRODUCT_TYPES_ENUMS } from '@/constants/commodity';
import {
  queryTemporaryGoodsListService,
  batchUpTemporaryGoodsService,
  batchOffTemporaryGoodsService,
  batchUpdateOffTimeService,
  batchUpdateBindCustomerService,
  advancedRelationService
} from '@/api/commodity/temporaryPurchasingGoods/temporaryProjectGoods';
import skusPage from '@/mixins/commodity/skusPage';
import selectCustomer from '../components/SelectCustomerDialog/mixins';
import { CacheKey as EditCacheKey } from './constants/edit';
import { getInitFormData } from '@/utils/getUtils';
import { setAuthBtnId } from '@/utils/bizUtils';
export default {
  mixins: [skusPage, selectCustomer],
  components: {
    BasicForm,
    SkusTable,
    BtnRender,
    RemoteSelect,
    SelectCustomerDialog,
    ActionDialog,
    ChangeLogDialog,
    SeniorLinkedDialog
  },
  data () {
    return {
      formItemList: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      tableInfo: {
        list: [],
        columns: TABLE_COLUMNS,
        loading: false,
        selection: []
      },
      dialogVisible: {
        batchUp: false,
        changeOffTime: false,
        changeBindCustomer: false,
        viewChangeLog: false
      },
      btnLoading: {
        batchUp: false,
        batchOff: false,
        changeOffTime: false
      },
      pageSizes: [10, 100, 1000],
      viewChangeLog: {
        skuNo: ''
      },
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }]
      },
      isShowPagination: true, // 是否展示分页，默认展示。使用高级查询时不展示分页
    }
  },
  mounted () {
    this.getTableData();
  },
  computed: {
    isToBatchUp () {
      const isEmptyTable = this.tableInfo.list.length === 0;
      if (isEmptyTable) return this.formData.skuState === '2';
      const isShowUpSku = this.tableInfo.list[0].skuState === '2';
      return isShowUpSku; // 当前展示上架时，展示下架按钮，反之展示上架按钮
    },
    hasNoSelection () {
      return this.tableInfo.selection.length === 0;
    },
    selectionUuids () {
      return this.tableInfo.selection.map(item => item.uuid);
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const batchUpBtn = { label: '批量上架', method: this.handleBatchUp };
      const batchDownBtn = { label: '批量下架', method: this.handleBatchDown, loading: this.btnLoading.batchOff };
      const batchChangeTimeBtn = { label: '修改下架日期', method: this.handleEditDownDate };
      const btnsBar = [
        { label: '高级查询', method: this.handleSeniorSearch, disabled: false, authLabel: '高级关联' },
        { label: '批量新增', method: this.handleBatchAdd, disabled: false },
        { label: '批量编辑', method: this.handleBatchEdit },
        this.isToBatchUp ? batchUpBtn : batchDownBtn,
        !this.isToBatchUp && batchChangeTimeBtn,
        { label: '换绑客户', method: this.handleChangeCustomer },
        { label: '转线索', method: this.handleToTemporaryPurchasing }
      ];
      // 按钮通用属性填充
      const finalBars = btnsBar.filter(item => item).map(item => ({
        ...item,
        type: 'primary',
        size: 'mini',
        disabled: item.disabled ?? this.hasNoSelection,
        hasAuth: item.hasAuth ?? true
      }));
      return getBtnsBar(h, finalBars, this.showBtn, 'start');
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '图文查看', method: this.handleViewImageText },
        { label: '图文编辑', method: this.handleEditImageText, hasAuth: true },
        { label: '修改日志', method: this.handleEditLog },
      ]
      return getTableAction({ h, row, actionList, showBtn: this.showBtn })
    },
    // 根据转临采状态禁用表格勾选 - 转换中的不可勾选
    checkSelectable ({ row }) {
      return row.transCollectStatus !== '2';
    },
    // 获取查询入参
    getSearchParams () {
      const [createStartTime = '', createEndTime = ''] = this.formData.createTime ?? [];
      const [offStartTime = '', offEndTime = ''] = this.formData.offTime ?? [];
      const formData = _.omit({
        ...this.formData,
        createStartTime,
        createEndTime,
        offStartTime,
        offEndTime
      }, ['createTime', 'offTime']);
      return { ...formData, ...this.paginationParams };
    },
    // 获取表格数据 by 查询表单
    async getTableData () {
      setAuthBtnId('查询');
      this.isShowPagination = true
      const data = this.getSearchParams();
      const loadingFn = state => { this.tableInfo.loading = state };
      const retData = await queryTemporaryGoodsListService(data, loadingFn);
      if (retData) {
        this.tableInfo.list = retData.results;
        this.setTotalNum(retData.totalNum);
      }
    },
    // 高级查询 设置表格数据
    async setTableDataBySeniorSearch (skuNos) {
      this.isShowPagination = false
      const data = { skuNos }
      const loadingFn = state => { this.tableInfo.loading = state }
      const res = await advancedRelationService(data, loadingFn)
      this.tableInfo.list = res?.retData ?? []
    },
    // 高级查询
    async handleSeniorSearch () {
      this.seniorLinked.visible = true
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 图文查看
    handleViewImageText (row) {
      this.skipToImagePage(row, 'view');
    },
    // 图文编辑
    handleEditImageText (row) {
      setAuthBtnId('图文编辑');
      this.skipToImagePage(row, 'edit');
    },
    // 修改日志
    handleEditLog (row) {
      this.dialogVisible.viewChangeLog = true;
      this.viewChangeLog.skuNo = row.skuNo;
    },
    // 批量新增
    handleBatchAdd () {
      setAuthBtnId('批量新增');
      this.$router.push({ name: 'temporaryProjectGoodsAdd' });
    },
    // 批量编辑
    handleBatchEdit () {
      setAuthBtnId('批量编辑');
      sessionStorage.setItem(EditCacheKey, JSON.stringify(this.selectionUuids))
      this.$router.push({ name: 'temporaryProjectGoodsEdit' });
    },
    // 批量上架
    handleBatchUp () {
      this.dialogVisible.batchUp = true;
    },
    // 批量下架
    handleBatchDown () {
      this.$confirm('商品下架后，销售端将不会被搜索及展示', '下架提示', {
        type: 'warning',
      }).then(() => {
        this.batchOffTemporaryProjectGoods();
      }).catch(() => {});
    },
    // 修改下架日期
    handleEditDownDate () {
      this.dialogVisible.changeOffTime = true;
    },
    // 换绑客户
    handleChangeCustomer () {
      this.dialogVisible.changeBindCustomer = true;
    },
    // 转临采
    handleToTemporaryPurchasing () {
      setAuthBtnId('转临采');
      const customerIds = this.tableInfo.selection.map(item => item.customerId)
      const hasMoreCustomer = (new Set(customerIds)).size > 1;
      if (hasMoreCustomer) return this.$message.warning('请勾选相同的客户');
      sessionStorage.setItem(CacheKey, JSON.stringify(this.selectionUuids));
      this.$router.push({ name: 'temporaryAddCode', query: { type: 3 } });
    },
    // 表单特殊清空
    handleClearForm () {
      this.clearCustomerInfo();
    },
    // 跳转图文页面
    skipToImagePage (row, type) {
      const { href } = this.$router.resolve({
        name: 'imageTextManage',
        query: {
          type,
          skuId: row.uuid,
          skuNo: row.skuNo,
          productType: PRODUCT_TYPES_ENUMS.TEMP_PROJECT,
        }
      });
      window.open(href, '_blank');
    },
    // 批量上架临时项目商品
    async batchUpTemporaryProjectGoods (result) {
      if (!result?.expectOffTime) return false;
      const { expectOffTime } = result;
      // newSkuState - 1为上架，2为下架; expectOffTime - 预计下架日期
      this.batchAction('batchUp', { newSkuState: '1', newOffTime: expectOffTime });
    },
    // 批量下架临时项目商品
    async batchOffTemporaryProjectGoods () {
      // newSkuState - 1为上架，2为下架
      this.batchAction('batchOff', { newSkuState: '2' });
    },
    // 批量修改下架日期
    async batchUpdateOffDate (result) {
      if (!result?.expectOffTime) return false;
      const { expectOffTime } = result;
      // expectOffTime - 预计下架日期
      this.batchAction('changeOffTime', { newOffTime: expectOffTime });
    },
    // 批量换绑客户
    batchChangeBindCustomer (result) {
      if (!result?.customerCode) return false;
      this.batchAction('changeBindCustomer', {
        newCustomerId: result.customerId,
        newCustomerNo: result.customerCode,
        newCustomerName: result.customerName,
      });
    },
    // 获取批量操作的实例对象
    getBatchActionInstance (type) {
      const batchUp = {
        msg: '上架成功',
        authName: '批量上架',
        request: batchUpTemporaryGoodsService,
      }
      const batchOff = {
        msg: '下架成功',
        authName: '批量下架',
        request: batchOffTemporaryGoodsService,
      }
      const changeOffTime = {
        msg: '下架日期修改成功',
        authName: '修改下架日期',
        request: batchUpdateOffTimeService
      }
      const changeBindCustomer = {
        msg: '客户换绑成功',
        request: batchUpdateBindCustomerService
      }
      const actionMaps = { batchUp, batchOff, changeOffTime, changeBindCustomer };
      return actionMaps[type] ?? {};
    },
    // 批量操作请求
    async batchAction (type, params) {
      const { msg, request, authName } = this.getBatchActionInstance(type);
      if (authName) setAuthBtnId(authName);
      const loadingFn = state => { this.btnLoading[type] = state };
      const data = {
        ...params,
        mdUuids: this.selectionUuids
      }
      const res = await request(data, loadingFn);
      if (res) {
        this.$message.success(msg);
        if (this.dialogVisible[type]) {
          this.dialogVisible[type] = false;
        }
        this.getTableData();
      }
    },
  }
}
</script>
